#pragma once
#include "CQNetBase.h"

namespace CQLIB {
	namespace CQNET
	{
		class LIBCQNET_API CQConnector_TCP : public std::enable_shared_from_this<CQConnector_TCP>
		{
		public:
			CQConnector_TCP(const std::string ip = DEF_IP, int port = 0, void* cb = nullptr, void* ptr = nullptr,
				io_service& io_ = CQIoServiceManager::obj()->get_io_service());
			~CQConnector_TCP();

			const int get_key()const { while (!csp->key)Sleep(10); return csp->key; }
			bool do_write(const std::string& msg);
			void close();
			void stop_io() { csp->stop_io(); }
		private:
			void async_connect(io_service& io_, const std::string ip = DEF_IP, int port = 0);
			void connect_handler(const boost_error_code& ec);
			bool do_read();
			bool on_read(const boost_error_code& ec, std::size_t length);
			bool on_write(const boost_error_code& ec);
			bool send_enc_key();
			void cb_connect_timeout();
		private:
			deadline_timer timer_;
			endpoint_type remote_endpoint_;
			callbacks_c* cb_;
			void* ptr_;

			CQSock_Ptr csp;
			static session_ptr session_;
		};

		typedef std::shared_ptr<CQConnector_TCP> Client_Ptr;
	}
}